<template>
  <base-modal
    class="material-sn-dialog-container"
    :show.sync="visible"
    :title="title"
    width="500px"
    append-to-body
  >
    <div class="material-sn-content">
      
      <el-form v-if="type === 'add' || type === 'edit'" ref="form" :model="form" :rules="rules" label-position="top">
        <el-form-item :label="$t('common.form.preview.materialVerifyEliminate.label1')" prop="snValue">
          <el-select
            class="searchMaterialSelect"
            v-model="form.snValue"
            filterable
            :placeholder="$t('common.form.preview.materialVerifyEliminate.placeholder2')"
            :loading="loading"
            :popper-append-to-body="false"
            @input="chooseSn"
          >
            <el-option
              v-for="(item, index) in snData"
              :key="`${item.value}${index}`"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

        </el-form-item>
      </el-form>

      <div class="bottom">
        <el-input type="textarea" v-model="snValue" :rows="8" :disabled="snValueDisabled"></el-input>
        <div v-if="type === 'readOnly'" class="tips">{{$t('common.form.tip.materialReturn.tips3')}}</div>
        <div v-if="type === 'add' || type === 'edit'" class="tips">{{$t('common.form.tip.materialReturn.tips4')}}</div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button v-if="type !== 'edit'" :disabled="pending" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button v-if="type === 'add' || type === 'edit'" type="primary" :disabled="pending" @click="verification">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-modal>
</template>
<script>
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';
/* util */
import Log from '@src/util/log.ts'
import i18n from '@src/locales'
export default {
  name: 'material-sn-dialog',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      pending: false,
      visible: false,
      loading: false,
      snData: [],
      form: {
        snValue: ''
      },
      rules: {
        snValue: { required: true, message: i18n.t('common.placeholder.selectSomething', {0: i18n.t('common.form.preview.materialReturn.tableLabel3')}), trigger: 'change' }
      },
      type: '',
      title: '',
      titleMap: {
        'add': i18n.t('common.base.addModule', {module: i18n.t('common.form.preview.materialReturn.tableLabel3')}),
        'edit': i18n.t('common.base.editModule', {module: i18n.t('common.form.preview.materialReturn.tableLabel3')}),
        'readOnly': i18n.t('common.base.viewModule', {module: i18n.t('common.form.preview.materialReturn.tableLabel3')})
      },
      snTextList: [],
      row: {},
      index: '',
      // 从物料申领中添加
      isMaterialApply: false
    }
  },
  computed: {
    snValue: {
      get(){
        return this.snTextList.join('\n')
      },
      set(v) {
        this.snTextList = v ? v.split('\n') : []
      }
    },
    snLength(){
      return this.snTextList.length
    },
    snValueDisabled() {
      return this.type === 'readOnly'
    }
  },
  methods: {
    open(type, row, index, isMaterialApply) {
      this.title = this.titleMap[type]
      this.type = type
      this.row = row
      this.index = index
      this.form.snValue = ''
      this.snTextList = row?.snList?.slice()
      this.isMaterialApply = isMaterialApply
      this.visible = true
      
      if(this.isMaterialApply) {
        // 从物料申领添加
        let snData = row.snData.map(item => {
          return {
            label: item,
            value: item,
          }
        })
        this.snData = snData
      } else {
        // 从仓库添加
        this.snData = []
        this.search()
      }
    },
    /**
     * @description 搜索SN
    */
    async search(keyword) {
      this.loading = true;
      try {
        let params = {
          keyword,
          // 库存id
          inventoryId: this.row.id 
        }
        let res = await WareHouseApi.getInventorySNList(params);
        this.loading = false;
        if (!res.success) return;
        this.snData = res.data.snList.map((item, index) => {
          return {
            label: item,
            value: item,
            ...item,
          }
        })
      } catch (error) {
        this.loading = false;
        Log.error(error, 'search')
      }
    },
    /**
     * @description 选择SN
    */
    chooseSn(value) {
      let haveSn = this.snTextList.findIndex(item => item === value) > -1
      if(haveSn) return this.$platform.toast(this.$t('common.form.tip.materialReturn.tips5'), 'warning')
      
      if(this.snLength >= this.row.number) return this.$platform.toast(this.$t('common.form.tip.materialVerifyEliminate.tips4'), 'warning')
      this.snTextList.push(value)
    },
    async verification() {
      
      if(this.snLength !== this.row.number) return this.$platform.toast(this.$t('common.form.tip.materialVerifyEliminate.tips4'), 'warning')

      // 校验库存中是否存在SN
      // let verificationSn = await this.validInventorySn()
      // if(!verificationSn) {
      //   let confirm = await this.$platform.confirm('当前物料SN有误，确认是否仍要办理？');
      //   if(!confirm) return
      // }

      return this.submit()
    },
    submit() {
      let data = this.data
      this.$set(data[this.index], 'snList', this.snTextList)

      this.$emit('changeSn', data)
      this.visible = false
    },
    /**
     * @description 校验SN
    */
    async validInventorySn() {
      let { materialId, warehouseId, positionId } = this.row
      let materialSnMap = {
        [materialId]: this.snTextList
      }
      let params = {
        warehouseId,
        positionId,
        materialSnMap
      }
      try {
        const data = await WareHouseApi.validInventorySn(params)
        const result = data.success && data?.data?.size < 1
        return result
      } catch (error) {
        Log.error(error, 'validInventorySn')
      }
    }
  }
}
</script>
<style lang="scss" scope>
.material-sn-content {
  padding: 10px;
  .bottom {
    padding: 0 4px;
    .tips {
      padding: 10px 0;
      font-size: 12px;
      color: #606266;
    }
  }
  
}
.el-textarea.is-disabled .el-textarea__inner {
  color: #606266 !important;
  background-color: #FFFFFF !important;
}
</style>